package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.model.vo.SkuHasStockVo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.exception.NoStockException;
import com.atguigu.gulimall.ware.feign.ProductFeignService;
import com.atguigu.gulimall.ware.model.vo.LockStockResult;
import com.atguigu.gulimall.ware.model.vo.WareSkuLockVo;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    WareSkuDao wareSkuDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();

        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)) {
            queryWrapper.eq("sku_id", skuId);
        }

        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)) {
            queryWrapper.eq("ware_id", wareId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //如果还没有这个库存操作 记录新增
        List<WareSkuEntity> wareSkuEntities = this.baseMapper.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (CollectionUtils.isEmpty(wareSkuEntities)) {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);
            //远程查询sku的名字 如果失败，无需回滚
            try {
                R r = productFeignService.querySkuName(skuId);
                if (r.getCode() == 0) {
                    Map<String, Object> data = (Map<String, Object>) r.get("skuInfo");
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {
            }
            this.baseMapper.insert(wareSkuEntity);
        } else {
            this.baseMapper.addStock(skuId, wareId, skuNum);
        }
    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {
        return skuIds.stream().map(skuId -> {
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();

            Long count = this.baseMapper.getSkuStock(skuId);

            skuHasStockVo.setSkuId(skuId);
            skuHasStockVo.setHasStock(count == null ? false : count > 0);
            return skuHasStockVo;
        }).collect(Collectors.toList());
    }

    /**
     * 为某个订单锁定库存
     * <p>
     * <p>
     * 默认运行时异常都会回滚
     */
    @Transactional(rollbackFor = NoStockException.class)
    @Override
    public boolean orderLockStock(WareSkuLockVo lockVo) {
        //1.找到每个商品项在哪些仓库有库存
        List<SkuWareHasStock> wareHasStockList = lockVo.getLocks().stream().map(item -> {
            SkuWareHasStock hasStock = new SkuWareHasStock();
            List<Long> wareIdList = wareSkuDao.listWareIdHasSkuStock(item.getSkuId());
            hasStock.setWareId(wareIdList);
            hasStock.setSkuId(item.getSkuId());
            hasStock.setCount(item.getCount());
            return hasStock;
        }).collect(Collectors.toList());
        //2.锁定库存
        for (SkuWareHasStock hasStock : wareHasStockList) {
            boolean skuStocked = false;
            List<Long> wareIdList = hasStock.getWareId();
            if (wareIdList == null && wareIdList.isEmpty()) {
                //没有任何仓库有这个商品的库存
                throw new NoStockException(hasStock.getSkuId());
            }
            for (Long wareId : wareIdList) {
                Integer count = wareSkuDao.lockSkuStock(hasStock.getSkuId(), wareId, hasStock.getCount());
                if (count == 1) {
                    skuStocked = true;
                    break;
                }
                //当前仓库锁定失败，重试下一个仓库
            }
            if (Boolean.FALSE.equals(skuStocked)) {
                //当前商品所有仓库都没有锁住
                throw new NoStockException(hasStock.getSkuId());
            }
        }
        return true;
    }

    @Data
    static class SkuWareHasStock {
        private Long skuId;
        private List<Long> wareId;
        private Integer count;
    }
}